import Vue from 'vue';
import {Base64} from 'js-base64';
import Cookies from 'js-cookie';
import API from '../../api/api';

const state = {
    login: null,
    user: null
};

const actions = {
    async login({commit}, user) {
        var form = new FormData();
        form['client_id'] = API.APP_CLIENT_ID;
        form['client_secret'] = API.APP_CLIENT_SECRET;
        form['grant_type'] = 'vc';
        form['username'] = user.username;
        form['password'] = user.password;
        form['vc'] = user.vercode;
        form['vc_token'] = user.verifyCodeId;
        form['scope'] = 'read write';
        var res = await Vue.http.post(API.LOGIN_API, form, {
            transformRequest: [function (data) {
                let ret = '';
                for (const it in data) {
                    ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&';
                }
                return ret;
            }],
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded'
            },
            auth: {
                username: API.APP_CLIENT_ID,
                password: API.APP_CLIENT_SECRET
            }
        });
        var accessToken = res.access_token;
        var userStr = Base64.decode(accessToken.split('.')[1]);
        var userJson = JSON.parse(userStr);
        var storeUser = {};
        storeUser.userId = userJson.userId;
        storeUser.userName = userJson.userName;
        storeUser.nickName = userJson.nickName;
        storeUser.logo = userJson.logo;
        storeUser.role = userJson.authorities;
        commit('SET_LOGIN_TOKEN', {
            token: res.access_token,
            exp: res.expires_in
        });
        commit('SET_REFRESH_TOKEN', res.refresh_token);
        commit('SET_LOGIN_USER', storeUser);
        return res;
    },
    async login2({commit}, user) {
        var form = new FormData();
        form['client_id'] = API.APP_CLIENT_ID;
        form['client_secret'] = API.APP_CLIENT_SECRET;
        form['grant_type'] = 'password';
        form['username'] = user.username;
        form['password'] = user.password;
        form['scope'] = 'read write';
        var res = await Vue.http.post(API.LOGIN_API, form, {
            transformRequest: [function (data) {
                let ret = '';
                for (const it in data) {
                    ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&';
                }
                return ret;
            }],
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded'
            },
            auth: {
                username: API.APP_CLIENT_ID,
                password: API.APP_CLIENT_SECRET
            }
        });
        var accessToken = res.access_token;
        var userStr = Base64.decode(accessToken.split('.')[1]);
        var userJson = JSON.parse(userStr);
        var storeUser = {};
        storeUser.userId = userJson.userId;
        storeUser.userName = userJson.userName;
        storeUser.nickName = userJson.nickName;
        storeUser.logo = userJson.logo;
        storeUser.role = userJson.authorities;
        commit('SET_LOGIN_TOKEN', {
            token: res.access_token,
            exp: res.expires_in
        });
        commit('SET_REFRESH_TOKEN', res.refresh_token);
        commit('SET_LOGIN_USER', storeUser);
        return res;
    },
    async refreshToken({commit}) {
        let refreshToken = sessionStorage.getItem('refresh_token');
        var form = new FormData();
        form['client_id'] = API.APP_CLIENT_ID;
        form['client_secret'] = API.APP_CLIENT_SECRET;
        form['grant_type'] = 'refresh_token';
        form['refresh_token'] = refreshToken;
        var res = await Vue.http.post(API.LOGIN_API, form, {
            transformRequest: [function (data) {
                let ret = '';
                for (const it in data) {
                    ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&';
                }
                return ret;
            }],
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded'
            },
            auth: {
                username: API.APP_CLIENT_ID,
                password: API.APP_CLIENT_SECRET
            }
        });
        if (res.access_token) {
            commit('SET_LOGIN_TOKEN', {
                token: res.access_token,
                exp: res.expires_in
            });
        }
        return res;
    },
    async getVerificationCode() {
        var res = await Vue.http.get(API.VERIFICATION_API);
        return res;
    }
};

const mutations = {
    SET_LOGIN_TOKEN(state, payload) {
        if (payload.token) {
            var date = new Date();
            date.setTime(date.getTime() + (payload.exp - 5) * 1000);
            Cookies.set('token', payload.token, {
                expires: date
            });
        } else {
            Cookies.remove('token');
        }
    },
    SET_REFRESH_TOKEN(state, token) {
        if (token) {
            sessionStorage.setItem('refresh_token', token);
        } else {
            sessionStorage.removeItem('refresh_token');
        }
    },
    SET_LOGIN_USER(state, user) {
        if (user) {
            sessionStorage.setItem('user', JSON.stringify(user));
        } else {
            sessionStorage.removeItem('user');
        }
    },
    LOGOUT(state, vm) {
        sessionStorage.removeItem('user');
        sessionStorage.removeItem('access');
        sessionStorage.removeItem('refresh_token');
        Cookies.remove('token');
        // 恢复默认样式
        let themeLink = document.querySelector('link[name="theme"]');
        themeLink.setAttribute('href', '');
        // 清空打开的页面等数据，但是保存主题数据
        let theme = '';
        if (localStorage.theme) {
            theme = localStorage.theme;
        }
        localStorage.clear();
        if (theme) {
            localStorage.theme = theme;
        }
    }
};

export default {
    state,
    actions,
    mutations
};
